{% extends 'base/base.html' %}
{% load static %}

{% block title %}超市地图 - 妙趣拾光锦盒{% endblock %}

{% block extra_css %}
<style>
    .map-container {
        height: 600px;
        border-radius: 15px;
        overflow: hidden;
        margin-bottom: 30px;
    }
    
    .market-list {
        max-height: 600px;
        overflow-y: auto;
    }
    
    .market-item {
        padding: 15px;
        border-radius: 10px;
        margin-bottom: 10px;
        transition: all 0.3s ease;
        cursor: pointer;
    }
    
    .market-item:hover {
        background-color: #f8f9fa;
        transform: translateY(-2px);
    }
    
    .market-item.active {
        background-color: #e9ecef;
        border-left: 4px solid #007bff;
    }
    
    .market-image {
        width: 50px;
        height: 50px;
        object-fit: cover;
        border-radius: 50%;
    }
    
    .rating-stars {
        color: #ffc107;
        font-size: 0.9rem;
    }
    
    .search-bar {
        margin-bottom: 20px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container mt-5">
    <!-- 面包屑导航 -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{% url 'blindbox:index' %}">首页</a></li>
            <li class="breadcrumb-item"><a href="{% url 'market:list' %}">合作超市</a></li>
            <li class="breadcrumb-item active" aria-current="page">超市地图</li>
        </ol>
    </nav>

    <h1 class="mb-4">超市地图</h1>
    
    <div class="row">
        <div class="col-md-8">
            <!-- 地图容器 -->
            <div id="mapContainer" class="map-container shadow-sm"></div>
        </div>
        
        <div class="col-md-4">
            <!-- 搜索栏 -->
            <div class="search-bar">
                <div class="input-group">
                    <input type="text" id="marketSearch" class="form-control" placeholder="搜索超市...">
                    <button class="btn btn-primary" type="button" id="searchBtn">
                        <i class="fas fa-search"></i>
                    </button>
                </div>
            </div>
            
            <!-- 超市列表 -->
            <div class="market-list">
                {% for market in markets %}
                <div class="market-item shadow-sm" data-id="{{ market.market_id }}" data-lng="{{ market.longitude }}" data-lat="{{ market.latitude }}">
                    <div class="d-flex align-items-center">
                        <img src="{{ market.image_url|default:'/static/images/default-market.jpg' }}" class="market-image me-3" alt="{{ market.name }}">
                        <div>
                            <h5 class="mb-1">{{ market.name }}</h5>
                            <div class="rating-stars mb-1">
                                {% for i in '12345'|make_list %}
                                    {% if forloop.counter <= market.rating %}
                                    <i class="fas fa-star"></i>
                                    {% else %}
                                    <i class="far fa-star"></i>
                                    {% endif %}
                                {% endfor %}
                            </div>
                            <small class="text-muted">
                                <i class="fas fa-map-marker-alt me-1"></i>{{ market.address|truncatechars:30 }}
                            </small>
                        </div>
                    </div>
                </div>
                {% empty %}
                <div class="text-center py-5">
                    <div class="mb-4">
                        <i class="fas fa-map-marked-alt" style="font-size: 4rem; color: #6c757d;"></i>
                    </div>
                    <h3>暂无超市数据</h3>
                    <p class="text-muted">目前还没有合作超市的信息</p>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=b7fb3f07380c4c27224ed3136b63dc04"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 初始化地图
    var map = new AMap.Map('mapContainer', {
        zoom: 11,
        viewMode: '3D'
    });
    
    // 存储所有标记点和信息窗体
    var markers = [];
    var infoWindows = {};
    
    // 创建点聚合
    var cluster;
    map.plugin(["AMap.MarkerCluster"], function() {
        cluster = new AMap.MarkerCluster(map, [], {
            gridSize: 80,
            maxZoom: 14
        });
    });
    
    // 添加地图控件
    map.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.ControlBar'], function(){
        map.addControl(new AMap.ToolBar());
        map.addControl(new AMap.Scale());
        map.addControl(new AMap.ControlBar({
            position: {
                right: '10px',
                top: '10px'
            }
        }));
    });
    
    // 创建超市标记点
    {% for market in markets %}
    {% if market.latitude and market.longitude %}
    (function() {
        var marketId = {{ market.market_id }};
        var position = [{{ market.longitude }}, {{ market.latitude }}];
        var marketName = '{{ market.name }}';
        var marketAddress = '{{ market.address|default:"" }}';
        var businessHours = '{{ market.business_hours|default:"" }}';
        var phone = '{{ market.phone|default:"" }}';
        var rating = {{ market.rating }};
        
        // 创建标记
        var marker = new AMap.Marker({
            position: position,
            title: marketName,
            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
        });
        
        markers.push(marker);
        
        // 创建信息窗体
        var content = '<div class="p-2">' +
            '<h5 class="mb-1">' + marketName + '</h5>' +
            '<p class="mb-1"><i class="fas fa-map-marker-alt text-danger me-1"></i> ' + marketAddress + '</p>';
            
        if (businessHours) {
            content += '<p class="mb-1"><i class="far fa-clock text-primary me-1"></i> ' + businessHours + '</p>';
        }
        
        if (phone) {
            content += '<p class="mb-1"><i class="fas fa-phone-alt text-success me-1"></i> ' + phone + '</p>';
        }
        
        content += '<p class="mb-0">' +
            '<a href="/market/detail/' + marketId + '/" class="btn btn-sm btn-primary mt-2">查看详情</a>' +
            '</p>' +
            '</div>';
            
        var infoWindow = new AMap.InfoWindow({
            content: content,
            anchor: 'bottom-center',
            offset: new AMap.Pixel(0, -30)
        });
        
        infoWindows[marketId] = {
            marker: marker,
            infoWindow: infoWindow
        };
        
        // 点击标记打开信息窗体
        marker.on('click', function() {
            // 关闭其他信息窗口
            Object.keys(infoWindows).forEach(function(key) {
                infoWindows[key].infoWindow.close();
            });
            
            // 打开当前信息窗口
            infoWindow.open(map, marker.getPosition());
            
            // 高亮对应的超市列表项
            highlightMarketItem(marketId);
        });
    })();
    {% endif %}
    {% endfor %}
    
    // 如果有标记点，添加到地图并自动调整视图
    if (markers.length > 0) {
        // 添加标记到聚合
        cluster.setMarkers(markers);
        
        // 自动调整视图以包含所有标记
        if (markers.length > 1) {
            map.setFitView();
        } else {
            map.setCenter(markers[0].getPosition());
            map.setZoom(15);
        }
    }
    
    // 超市列表项点击事件
    var marketItems = document.querySelectorAll('.market-item');
    marketItems.forEach(function(item) {
        item.addEventListener('click', function() {
            var marketId = this.getAttribute('data-id');
            var lng = this.getAttribute('data-lng');
            var lat = this.getAttribute('data-lat');
            
            if (lng && lat && infoWindows[marketId]) {
                // 关闭所有信息窗口
                Object.keys(infoWindows).forEach(function(key) {
                    infoWindows[key].infoWindow.close();
                });
                
                // 移动到该标记并打开信息窗口
                var marker = infoWindows[marketId].marker;
                var infoWindow = infoWindows[marketId].infoWindow;
                
                map.setCenter(marker.getPosition());
                map.setZoom(15);
                infoWindow.open(map, marker.getPosition());
                
                // 高亮当前超市列表项
                highlightMarketItem(marketId);
            }
        });
    });
    
    // 高亮超市列表项
    function highlightMarketItem(marketId) {
        marketItems.forEach(function(item) {
            item.classList.remove('active');
            if (item.getAttribute('data-id') == marketId) {
                item.classList.add('active');
                // 滚动到可见区域
                item.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
        });
    }
    
    // 超市搜索功能
    var searchInput = document.getElementById('marketSearch');
    var searchBtn = document.getElementById('searchBtn');
    
    // 搜索按钮点击事件
    if (searchBtn) {
        searchBtn.addEventListener('click', function() {
            filterMarkets();
        });
    }
    
    // 搜索框输入事件
    if (searchInput) {
        searchInput.addEventListener('keyup', function(e) {
            if (e.key === 'Enter') {
                filterMarkets();
            }
        });
    }
    
    // 过滤超市列表
    function filterMarkets() {
        var searchValue = searchInput.value.toLowerCase();
        
        marketItems.forEach(function(item) {
            var marketName = item.querySelector('h5').textContent.toLowerCase();
            var marketAddress = item.querySelector('small').textContent.toLowerCase();
            
            if (marketName.includes(searchValue) || marketAddress.includes(searchValue)) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    }
});
</script>
{% endblock %} 